﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GDoc.Domain.Services;
using System.Web.Routing;
using System.Web.Mvc;
using GDoc.Domain;
using System.IO;

namespace GDoc.Web.Models
{
    public class FileSystemEntryModel
    {
        public FileSystemEntryModel(FileSystemEntry entry, RequestContext context)
        {
            var url = new UrlHelper(context);

            AccountId = entry.AccountId;
            Name = entry.Name;
            Path = entry.Path;
            FullPath = entry.FullPath;
            this.Type = entry.Type == 0 ? "Carpeta" : "Archivo" + GetExtention(entry.Name);
            Size = entry.Size.HasValue ? GetSizeText(entry.Size.Value) : string.Empty;
            Modified = entry.Modified.ToString("dd-MMM-yyyy HH:mm");
            Created = entry.Created.ToString("dd-MMM-yyyy HH:mm");
            if (entry.Type == 0)
                _Ref = url.Action("Browse", "Files", new { path = entry.FullPath });
            else if (entry.Type == 1)
                _Ref = url.Action("GetFile", "Files", new { path = entry.FullPath });
        }

        private string GetExtention(string fileName)
        {
            string extension = fileName.Split(new char[] { '.', ' ' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();

            if (extension == null)
                return String.Empty;
            else
                return " " + extension.ToUpper();
        }

        private string GetSizeText(long bytes)
        {
            if (bytes < 0)
                return "wrong size";
            if (bytes < 1024) // less than 1 KB
                return String.Format("{0} Bytes", bytes);
            if (bytes < 1048576) // less than 1 MB
                return String.Format("{0} KB", Math.Round((decimal)bytes / 1024, 1));
            if (bytes < 1073741824) // less than 1 GB
                return String.Format("{0} MB", Math.Round((decimal)bytes / 1048576, 1));
            if (bytes < 1099511627776) // less than 1 TB
                return String.Format("{0} GB", Math.Round((decimal)bytes / 1073741824, 1));
            else
                return String.Format("{0} TB", Math.Round((decimal)bytes / 1099511627776, 1));
        }

        public string Name { get; set; }
        public string Path { get; set; }
        public string FullPath { get; set; }
        public string Type { get; set; }
        public string Size { get; set; }
        public string Created { get; set; }
        public string Modified { get; set; }
        public string _Ref { get; set; }
        public long AccountId { get; set; }
    }


    public class FilesBrowseModel
    {
        public string Path { get; set; }

        public Account Account { get; set; }

        public string[] DirectoryTree { get; set; }
    }

}